運用 Cli 部署 Vue專案 到 GitHub Pages


Posted by hoyi-23 on 2021-08-15

前情提要:
使用 Vue Cli 來建置Vue專案


上一篇文章有提到To create a production build, run npm run build.
在佈署一個專案前都會先輸入npm run build,然後打包後的檔案就會出現在dist/目錄下。
現在要來學習運用一個指令部署 Vue Cli 到 GitHub Pages。
總共有三個步驟

  1. 建立vue.config.js
  2. 建立deploy.sh
  3. 修改gitignore

第一步: 建立vue.config.js

vue.config.js 中設置正確的 publicPath
有兩種情況:

  1. 打算將專案部署到https://<USERNAME>.github.io/ 上, 那麼publicPath將預設為/。可以忽略這個參數。
  2. 打算將專案部署到https://<USERNAME>.github.io/<REPO>上,那麼就要將publicPath設為"/<REPO>/"

範例: REPO => vueProject
publicPath用來指定要部署的路徑。

module.exports = {
  publicPath: process.env.NODE_ENV === 'production'
    ? '/vueProject/'
    : '/'
}

第二步: 建立deploy.sh

#!/usr/bin/env sh

# 當發生錯誤時終止
set -e

# 建構 (build這裡做的就是幫我們把Vue轉成HTML/JS/CSS,並放入dist)
npm run build

# save the lastest commit hash as a string
LOGSTRING=$(git log)
COMMIT=$(echo $LOGSTRING | awk '{print $2}')

# cd 到建構輸出的目錄下
cd dist

# 如果要部署到自定義域名
# echo 'www.example.com' > CNAME

git init
git add -A //加入整個dist
git commit -m "deploy (commit: $COMMIT)"

# 部署到 https://<USERNAME>.github.io
# git push -f git@github.com:<USERNAME>/<USERNAME>.github.io.git master

# 部署到 https://<USERNAME>.github.io/<REPO>
git push -f git@github.com:<USERNAME>/<REPO>.git master:gh-pages

cd ..

修改 .gitignore

node_modules
dist

完整執行(終端機操作)

前情: 已經有了一個專案,然後要打包檔案放在dist/目錄下。
vue-cli-service build / npm run build
它就會依照上面的指令操作囉!


#gh-page







Related Posts

CSS 起手式

CSS 起手式

來寫個氣象機器人吧!(Part 2)

來寫個氣象機器人吧!(Part 2)

LeetCode JS Easy 2704. To Be Or Not To Be

LeetCode JS Easy 2704. To Be Or Not To Be


Comments